package com.yq;

import java.io.File;
import java.text.NumberFormat;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Image;

public class DoubleFile
{
    
    protected Shell shlDoublefile;
    private Text txt_path;
    private Label lb_size;
    private Label label_num;
    private List list;
    
    private DFileList fileList = null;
    private boolean searching = false;
    
    public static DoubleFile instance;
    private Label lb_msg;
    private Label priview;
    private Button button;
    private boolean canPriview;
    private boolean sameExt;
    private Button button_1;
    private Button button_2;
    
    /**
     * Launch the application.
     * @param args
     */
    public static void main(String[] args)
    {
        try
        {
            instance = new DoubleFile();
            instance.open();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    public void KeyPressed(Event event) {
        switch (event.keyCode) {
            case 'a':
            case 'A':
            case SWT.LEFT:
                prev();
                break;
            case 'd':
            case 'D':
            case SWT.RIGHT:
                next();
                break;
            case 'q':
            case 'Q':
            case SWT.DEL:
                browse();
                break;
            case 'o':
            case 'O':
            case SWT.CR:
                openFile();
                break;
            case 'c':
            case 'C':
                deleteFile();
                break;
            case 'n':
            case 'N':
                search();
                break;
            case 's':
            case 'S':
                selectNext();
                break;
            case 'w':
            case 'W':
                selectPrev();
                break;
        }
    }
    
    public void selectPrev() {
        if (fileList == null || fileList.list.size() < 2) {
            return;
        }
        int selectIndex = list.getSelectionIndex();
        if (selectIndex > 0) {
            selectIndex--;
        } else {
            selectIndex = fileList.list.size() - 1;
        }
        list.setSelection(selectIndex);
    }
    
    public void selectNext() {
        if (fileList == null || fileList.list.size() < 2) {
            return;
        }
        int selectIndex = list.getSelectionIndex();
        if (selectIndex < fileList.list.size() - 1) {
            selectIndex++;
        } else {
            selectIndex = 0;
        }
        list.setSelection(selectIndex);
    }
    
    /**
     * Open the window.
     */
    public void open()
    {
        Display display = Display.getDefault();
        display.addFilter(SWT.KeyDown, new Listener()
        {
            
            @Override
            public void handleEvent(Event event)
            {
                KeyPressed(event);
            }
        });
        createContents();
        shlDoublefile.open();
        shlDoublefile.layout();
        while (!shlDoublefile.isDisposed())
        {
            if (!display.readAndDispatch())
            {
                display.sleep();
            }
        }
        System.exit(0);
    }
    
    /**
     * Create contents of the window.
     */
    protected void createContents()
    {
        shlDoublefile = new Shell();
        shlDoublefile.setSize(956, 750);
        shlDoublefile.setText("DoubleFile");
        
        Label lblPath = new Label(shlDoublefile, SWT.NONE);
        lblPath.setBounds(10, 10, 45, 17);
        lblPath.setText("\u76EE\u5F55\uFF1A");
        
        txt_path = new Text(shlDoublefile, SWT.BORDER);
        txt_path.setEditable(false);
        txt_path.setText("C:\\");
        txt_path.setBounds(61, 7, 762, 23);
        
        Button btnNewButton = new Button(shlDoublefile, SWT.NONE);
        btnNewButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                browse();
            }
        });
        btnNewButton.setBounds(844, 5, 80, 27);
        btnNewButton.setText("\u6D4F\u89C8&Q");
        
        Button btnNewButton_1 = new Button(shlDoublefile, SWT.NONE);
        btnNewButton_1.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                search();
            }
        });
        btnNewButton_1.setBounds(844, 38, 80, 27);
        btnNewButton_1.setText("\u641C\u7D22&N");
        
        lb_size = new Label(shlDoublefile, SWT.NONE);
        lb_size.setBounds(10, 43, 172, 17);
        
        Button btna = new Button(shlDoublefile, SWT.NONE);
        btna.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                prev();
            }
        });
        btna.setBounds(34, 80, 55, 55);
        btna.setText("\u4E0A\u4E00\u4E2A&A");
        
        Button btnd = new Button(shlDoublefile, SWT.NONE);
        btnd.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                next();
            }
        });
        btnd.setText("\u4E0B\u4E00\u4E2A&D");
        btnd.setBounds(34, 181, 55, 55);
        
        label_num = new Label(shlDoublefile, SWT.NONE);
        label_num.setAlignment(SWT.CENTER);
        label_num.setBounds(10, 147, 102, 17);
        label_num.setText("0/0");
        
        Button btnq = new Button(shlDoublefile, SWT.NONE);
        btnq.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                deleteFile();
            }
        });
        btnq.setBounds(844, 224, 80, 27);
        btnq.setText("\u5220\u9664\u6587\u4EF6&C");
        
        list = new List(shlDoublefile, SWT.BORDER);
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseDown(MouseEvent e) {
                onSelect();
            }
        });
        list.setBounds(118, 66, 715, 185);
        
        Button btno = new Button(shlDoublefile, SWT.NONE);
        btno.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                openFile();
            }
        });
        btno.setBounds(844, 191, 80, 27);
        btno.setText("\u6253\u5F00\u76EE\u5F55&O");
        
        lb_msg = new Label(shlDoublefile, SWT.NONE);
        lb_msg.setAlignment(SWT.RIGHT);
        lb_msg.setBounds(140, 43, 688, 17);
        
        priview = new Label(shlDoublefile, SWT.NONE);
        priview.setBounds(10, 267, 914, 434);
        
        button = new Button(shlDoublefile, SWT.CHECK);
        button.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                sameExt = button.getSelection();
            }
        });
        button.setBounds(844, 80, 98, 17);
        button.setText("\u540C\u7C7B\u578B");
        
        button_1 = new Button(shlDoublefile, SWT.CHECK);
        button_1.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                canPriview = button_1.getSelection();
                onSelect();
            }
        });
        button_1.setBounds(844, 120, 98, 17);
        button_1.setText("\u9884\u89C8");
        
        button_2 = new Button(shlDoublefile, SWT.NONE);
        button_2.addSelectionListener(new SelectionAdapter() {
        	@Override
        	public void widgetSelected(SelectionEvent e) {
        		MessageBox mb = new MessageBox(shlDoublefile, SWT.OK | SWT.CANCEL);
        		mb.setMessage("确定要删除所有重复文件吗？(将随机保留其中一个)");
        		mb.setText("删除所有文件");
        		if (mb.open() == SWT.OK) {
        			deleteAllFile();
        		}
        	}
        });
        button_2.setBounds(844, 158, 80, 27);
        button_2.setText("\u5220\u9664\u6240\u6709");
        
    }
    
    public void onSelect() {
        if (searching) {
            return;
        }
        setPriview(null);
        if (checkSearch()) {
            File file = fileList.getIndex(list.getSelectionIndex());
            if (file != null && file.exists()) {
                String name = file.getName();
                if (isImage(name)) {
                    setPriview(file.getPath());
                }
            }
        }
    }
    
    public boolean isImage(String name) {
        name = name.toLowerCase();
        if (name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png") || name.endsWith(".bmp") || name.endsWith(".gif") || name.endsWith(".tiff") || name.endsWith(".icon")) {
            return true;
        }
        return false;
    }
    
    public void setPriview(String filePath) {
        if (filePath == null || !canPriview) {
            priview.setImage(null);
            return;
        }
        Image img = new Image(Display.getDefault(), filePath);
        priview.setImage(img);
    }
    
    public void openFile() {
        if (searching) {
            return;
        }
        if (checkSearch()) {
            fileList.openFile(list.getSelectionIndex());
        }
    }
    
    private boolean checkSearch() {
        if (fileList == null) {
            boolean rtn = MessageDialog.openConfirm(shlDoublefile, "未搜索目录", "是否开始搜索？");
            if (rtn) {
                search();
            }
            return false;
        }
        return true;
    }
    
    public void prev() {
        if (searching) {
            return;
        }
        fileList = FileManage.getInstance().getPrev();
        update();
    }
    
    public void next() {
        if (searching) {
            return;
        }
        fileList = FileManage.getInstance().getNext();
        update();
    }
    
    public void search() {
        if (searching) {
            return;
        }
        searching = true;
        showMessage("搜索中......");
        FileManage.search(txt_path.getText(), sameExt);
    }
    
    public void browse() {
        DirectoryDialog dir = new DirectoryDialog(shlDoublefile);
        dir.setText("指定目录");
        dir.setFilterPath("D:/");
        dir.setMessage("请选择相应的文件夹");
        String selectedDir = dir.open();
        if (selectedDir != null) {
            txt_path.setText(selectedDir);
        }
    }
    
    public void deleteFile() {
        if (searching) {
            return;
        }
        if (checkSearch()) {
            fileList.deleteFile(list.getSelectionIndex());
        }
    }
    
    public void deleteAllFile() {
        if (searching) {
            return;
        }
        if (checkSearch()) {
            FileManage.getInstance().removeAll();
        }
    }
    
    /** 搜索线程调用此方法 */
    public void searchFinish() {
        fileList = FileManage.getInstance().getCurrent();
        searching = false;
        if (!Display.getDefault().isDisposed()) {
            Runnable runnable = new Runnable()
            {
                @Override
                public void run()
                {
                    update();
                    showMessage("搜索完成！");
                }
            };
            Display.getDefault().syncExec(runnable);
        }
    }
    
    public void deleteUpdate() {
        fileList = FileManage.getInstance().getCurrent();
        update();
    }
    
    public void update() {
        if (fileList == null) {
        	lb_size.setText("");
        	label_num.setText("");
        	list.removeAll();
            return;
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        lb_size.setText("" + nf.format(fileList.fileSize) + " bytes");
        label_num.setText((FileManage.getInstance().getCurrentIndex() + 1) + " / " + FileManage.getInstance().size());
        list.removeAll();
        String[] nameList = fileList.getList();
        for (int i = 0; i < nameList.length; i++)
        {
            list.add(nameList[i]);
        }
        list.setSelection(0);
        onSelect();
    }
    
    public void showMessage(String msg) {
        lb_msg.setText(msg);
    }
}
